package com.shire.shire_interface.controller.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.utils.JsonFormat;
import com.shire.shire_interface.common.utils.StrUtils;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.controller.kf.WebSocketController;
import com.shire.shire_interface.model.accounts.UserAccount;
import com.shire.shire_interface.model.group.WxGroupQrcode;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.service.account.WxAccountService;
import com.shire.shire_interface.service.friend.WxFriendLogService;
import com.shire.shire_interface.service.friend.WxFriendService;
import com.shire.shire_interface.service.group.WxGroupService;
import com.shire.shire_interface.service.group.impl.WxGroupQrcodeService;
import com.shire.shire_interface.service.validation.WxValidationRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/we")
public class ApiAddressController extends BaseController {

    @Autowired
    private WxFriendService wxFriendService;
    @Autowired
    private WxGroupService wxGroupService;

    @Autowired
    private WxAccountService wxAccountService;
    @Resource
    private WxValidationRecordService validationRecordService;
    @Resource
    private WxFriendLogService friendLogService;
    @Resource
    private WxGroupQrcodeService groupQrcodeService;

    private static Logger logger = LoggerFactory.getLogger(ApiAddressController.class);/**
     * @param request
     * @param body
     * @return
     */
    @RequestMapping("/receiveAddress.wx")
    public Map<String, Object> syncFriends(HttpServletRequest request, @RequestBody(required = false) String body) {
        WxAccount account = wxAccountService.getWxAccountById(getCurrentStation(request).getWxaccountid());
        if (account == null)
            return responseFailure("需要绑定帐号");

        logger.debug("更新通讯录列表，wxAccount = {}, body={}", account.getWxid(), body);
        body = StrUtils.getNullStr(body).trim();
        try{
            Map<String, Object> map = JsonFormat.toMap(body);
            if(map==null){
                return responseFailure("请求参数错误！");
            }
            String type = (String)map.get("type");
            if(StrUtils.isBlank(type)){
                return responseFailure(30000, "type参数错误");
            }
            List<Map<String,Object>> friends = (List<Map<String, Object>>)map.get("friends");
            List<Map<String,Object>> groups = (List<Map<String, Object>>)map.get("groups");

            int friendChanged = 0;
            if(friends!=null && friends.size()>0){
                wxFriendService.syncFriends(type, friends, account);
                friendChanged = 1;
            }

            if(groups!=null && groups.size()>0){

                wxGroupService.syncGroups(type, groups, account);
            }
            JSONObject syncWs = new JSONObject();
            syncWs.put("opType",8);
            syncWs.put("wxAccount", account.getWxid());
            syncWs.put("friendChanged", friendChanged);
            List<UserAccount> list = wxAccountService.getSystemUserByWxid(account.getWxid());
            for(UserAccount acc : list) {
                WebSocketController.sendMessage(acc.getUserId() + "", syncWs.toJSONString());
            }
        }
        catch (Exception e){
            logger.error("从CRK同步好友列表异常[wxAccount="+account.getWxid()+"]：", e);
            e.printStackTrace();
            return responseFailure("系统错误！");
        }
        return responseSuccess();
    }

    @RequestMapping("/receiveVerification.wx")
    public Map<String, Object> syncVerification(HttpServletRequest request, @RequestBody(required = false) JSONArray validationRecords) {
        WxAccount account = wxAccountService.getWxAccountById(getCurrentStation(request).getWxaccountid());
        if (account == null)
            return responseFailure("需要绑定帐号");
        validationRecordService.syncValidationForAccount(account, validationRecords);

        return responseSuccess();
    }
    @RequestMapping("/receiveGroupQrcode.wx")
    public Map<String, Object>receiveGroupQrcode(HttpServletRequest request, @RequestBody JSONObject body){
        String wxId = body.getString("wxId");
        String imgdata = body.getString("imgdata");
        try{
            WxAccount account = wxAccountService.getWxAccountById(getCurrentStation(request).getWxaccountid());
            if (account == null)
                return responseFailure("需要绑定帐号");
            WxGroupQrcode groupQrcode = groupQrcodeService.getGroupQrcode(account.getWxid(),wxId);
            if (groupQrcode == null){
                groupQrcode = new WxGroupQrcode();
                groupQrcode.setGroupno(wxId);
                groupQrcode.setWxaccount(account.getWxid());
                groupQrcode.setQrcode(imgdata);
            }else {
                groupQrcode.setQrcode(imgdata);
            }
            logger.info("同步群二维码 acccount:" + groupQrcode.getWxaccount() +" groupno:" + groupQrcode.getGroupno());
            groupQrcodeService.saveGroupQrcode(groupQrcode);
        }catch (Exception e){
            e.printStackTrace();
            return responseFailure(e.getMessage());
        }
        return responseSuccess();
    }

}
